package cn.itsource.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import cn.itsource.bean.*;
import cn.itsource.config.PageList;
import cn.itsource.mapper.SearchMasterMessageMapper;
import cn.itsource.mapper.SearchMasterMsgMapper;
import cn.itsource.query.SearchMasterQuery;
import cn.itsource.service.IPetTypeService;
import cn.itsource.service.ISearchMasterLogService;
import cn.itsource.service.ISearchMasterMessageService;
import cn.itsource.service.ISearchMasterMsgService;
import cn.itsource.util.JsonResult;
import cn.itsource.util.MyUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.logging.log4j.util.Strings;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static cn.itsource.util.PetHomeConstant.SEARCH_MASTER.SEARCH_MASTER_PASS;
import static cn.itsource.util.PetHomeConstant.SEARCH_MASTER.SEARCH_MASTER_PENDING;
import static cn.itsource.util.PetHomeConstant.SEARCH_MSG.SEARCH_MSG_PENDING;
import static cn.itsource.util.RedisContants.LOGIN_USER_KEY;

/**
 * @author : 张金铭
 * @description :
 * @create :2022-11-20 17:38:00
 */
@Service
public class SearchMasterMessageServiceImpl extends ServiceImpl<SearchMasterMessageMapper, SearchMasterMessage> implements ISearchMasterMessageService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IPetTypeService petTypeService;

    @Resource
    private ISearchMasterMsgService searchMasterMsgService;

    @Resource
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Resource
    private ISearchMasterLogService searchMasterLogService;


    /**
     * 新增审核申请
     * @param searchMasterMessage
     * @return
     */
    @Override
    public JsonResult sendMessage(SearchMasterMessage searchMasterMessage) {
        //将狗品种集合取最后一位放到狗的品种中
        Long typeId = Long.valueOf(searchMasterMessage.getPetTypeIds().get(searchMasterMessage.getPetTypeIds().size() - 1));
        searchMasterMessage.setPetType(typeId);
        //设置默认状态
        searchMasterMessage.setState(SEARCH_MASTER_PENDING);
        //获取发布人的uid，写入其中
        Long uid = MyUtils.getUid(stringRedisTemplate);
        searchMasterMessage.setUserId(uid);

        //TODO 检查次信息是否已经被该用户存入过？

        //将该信息存入待审核
        this.save(searchMasterMessage);
        return JsonResult.success("发布成功，待审核中!");
    }

    @Override
    public JsonResult getPage(SearchMasterQuery query) {
        Page<SearchMasterMessage> page = new Page<>();

        LambdaQueryWrapper<SearchMasterMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SearchMasterMessage::getState,SEARCH_MASTER_PENDING);
        queryWrapper.ge(Strings.isNotEmpty(query.getStartTime()),SearchMasterMessage::getCreateTime,query.getStartTime()).le(Strings.isNotEmpty(query.getEndTime()),SearchMasterMessage::getCreateTime,query.getEndTime());
        queryWrapper.like(Strings.isNotEmpty(query.getKeyword()),SearchMasterMessage::getName,query.getKeyword())
        .or().like(Strings.isNotEmpty(query.getKeyword()),SearchMasterMessage::getTitle,query.getKeyword())
        .or().like(Strings.isNotEmpty(query.getKeyword()),SearchMasterMessage::getAddress,query.getKeyword());


        Page<SearchMasterMessage> messagePage = this.page(page, queryWrapper);
        List<SearchMasterMessage> records = messagePage.getRecords();
        records= records.stream().map(item -> {
            Long petType = item.getPetType();
            if (petType != null) {
                PetType byId = petTypeService.getById(petType);
                String name = byId.getName();
                item.setPetTypeName(name);
            }
            item.setGenderName(item.getGender()?"绅士":"淑女");
            return item;
        }).collect(Collectors.toList());

        Long total = messagePage.getTotal();

        PageList<SearchMasterMessage> pageList = new PageList<>();
        pageList.setTotal(total);
        pageList.setList(records);

        return JsonResult.success(pageList);
    }

    @Override
    @Transactional
    public JsonResult pass(SearchMasterMsg msg, HttpServletRequest request) {
        //获取该id，
        Long id = msg.getId();
        //更新信息状态状态，查询得到具体数据，并拷贝
        SearchMasterMessage message = this.getById(id);
        message.setState(SEARCH_MASTER_PASS);
        this.updateById(message);
        BeanUtil.copyProperties(message,msg);
        //设置待处理,接单店铺null
        msg.setState(SEARCH_MSG_PENDING);
        msg.setId(null);
        //将获取到的数据存入,再获取id
        searchMasterMsgService.save(msg);

        //更新日志
        SearchMasterLog masterLog = BeanUtil.copyProperties(message, SearchMasterLog.class);
        masterLog.setId(null);
        masterLog.setMsgId(id);
        masterLog.setNote(msg.getNote());


        //从缓存中获取审核人员数据数据
        String token = request.getHeader("token");
        String emp = stringRedisTemplate.opsForValue().get(LOGIN_USER_KEY + token);
        Employee employee = JSONUtil.toBean(emp, Employee.class);
        Long employeeId = employee.getId();
        masterLog.setAuditId(employeeId);

        //加入日志
        searchMasterLogService.save(masterLog);
        return JsonResult.success("OK");
    }
}
